package testJdk.commonUse.array;

public class ArrayFinder {
    public int indexOf(int[] array, int value) {
        int low = 0;
        int high = array.length;
        int middle;

        while (low <= high) {
            middle = (low + high) / 2;//获取本次查找的中间数的下标
            this.print(array, middle);

            try {
                if (array[middle] == value) return middle;
            } catch (ArrayIndexOutOfBoundsException e) {//捕获游标越界异常
                return -1;
            }

            //二分查找的精华，如果第一轮中间值不等于传入值，分情况讨论
            if (value < array[middle]) {
                high = middle - 1;//缩小取中间值的范围
            } else {
                low = middle + 1;//扩大取中间值的范围
            }
        }

        return -1;
    }

    private void print(int[] array, int middle) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i == middle) System.out.print("*");
            System.out.print(" ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ArrayFinder arrayFinder = new ArrayFinder();
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

        int result = arrayFinder.indexOf(array, -10);
        System.out.println("result:" + result);
    }

}
